<template>
  <div>
    <el-menu
      v-model:default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      @select="index => (activeIndex = index)"
    >
      <el-menu-item index="1">项目需求</el-menu-item>
      <el-menu-item index="2">我的任务</el-menu-item>
    </el-menu>
    <div v-if="activeIndex === '1'" style="margin-top: 10px">
      项目： <project-selector v-model="projectId" select-first /> &nbsp;
      状态：<el-select v-model="query.status" style="width: 200px" multiple>
        <el-option
          v-for="(v, i) in demandStatus"
          :key="i"
          :label="v"
          :value="i"
        />
      </el-select>
      &nbsp; 需求名称：<el-input
        v-model="query.keyword"
        style="width: 200px"
        placeholder="需求名称"
      />

      &nbsp;
      <el-button type="primary" @click="openAddDemand">创建需求</el-button>
      <el-table
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px"
        row-key="id"
      >
        <el-table-column prop="name" label="需求名称" />
        <el-table-column prop="creator.nickName" label="创建人" />
        <el-table-column prop="charge.nickName" label="负责人" />
        <el-table-column prop="priority" label="优先级">
          <template #default="scope">
            {{ priorityStatus[scope.row.priority] }}
          </template>
        </el-table-column>
        <el-table-column prop="beginTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />

        <el-table-column prop="status" label="状态" width="100px">
          <template #default="scope">
            {{ demandStatus[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="openDemandDetails(scope.row.id)"
              >详情</el-button
            >
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              confirm-button-type="danger"
              title="是否确定删除项目"
              @confirm="deleteDemandFun(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="activeIndex === '2'" style="margin-top: 10px">
      项目： <project-selector v-model="projectId" clearable /> &nbsp;
      状态：<el-select v-model="query.status" style="width: 200px" multiple>
        <el-option
          v-for="(v, i) in demandStatus"
          :key="i"
          :label="v"
          :value="i"
        />
      </el-select>
      &nbsp; 需求名称：<el-input
        v-model="query.keyword"
        style="width: 200px"
        placeholder="需求名称"
      />

      &nbsp;
      <el-table
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px"
        row-key="id"
      >
        <el-table-column prop="name" label="需求名称" />
        <el-table-column prop="projectName" label="所属项目" />
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            {{ demandType[scope.row.type] }}
          </template>
        </el-table-column>
        <el-table-column prop="creator.nickName" label="创建人" />
        <el-table-column prop="charge.nickName" label="负责人" />
        <el-table-column prop="priority" label="优先级">
          <template #default="scope">
            {{ priorityStatus[scope.row.priority] }}
          </template>
        </el-table-column>
        <el-table-column prop="beginTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />

        <el-table-column prop="status" label="状态" width="100px">
          <template #default="scope">
            {{ demandStatus[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="openDemandDetails(scope.row.id)"
              >详情</el-button
            >
            <!--            <el-popconfirm-->
            <!--              confirm-button-text="确定"-->
            <!--              cancel-button-text="取消"-->
            <!--              confirm-button-type="danger"-->
            <!--              title="是否确定删除项目"-->
            <!--              @confirm="deleteDemandFun(scope.row.id)"-->
            <!--            >-->
            <!--              <template #reference>-->
            <!--                <el-button type="danger">删除</el-button>-->
            <!--              </template>-->
            <!--            </el-popconfirm>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 常规数据分页开始 -->
    <el-pagination
      v-model::current-page="query.current"
      v-model:page-size="query.size"
      style="margin-top: 10px"
      :total="pageTotal"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      layout="prev,pager,next,jumper,sizes,total"
      @size-change="pageSizeChange"
      @current-change="currPageChange"
    />
    <el-dialog
      v-model="addDemandDisplay"
      title="创建需求"
      width="500"
      destroy-on-close
    >
      <el-form label-width="auto" :model="demandForm" class="demo-form-inline">
        <el-form-item label="需求名称">
          <el-input
            v-model="demandForm.name"
            placeholder="请输入需求名称"
            clearable
            style="max-width: 240px"
          />
        </el-form-item>
        <el-form-item label="负责人">
          <user-selector v-model="demandForm.chargeId" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="demandForm.startTime"
            style="max-width: 240px"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="demandForm.endTime"
            style="max-width: 240px"
            format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="需求描述">
          <el-input
            v-model="demandForm.description"
            style="max-width: 240px"
            type="textarea"
          />
        </el-form-item>
        <div>
          <el-form-item label="需求相关文件">
            <el-upload
              v-model:file-list="attachmentsFileList"
              :http-request="handleFileUpload"
              style="width: 240px"
              multiple
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </div>
        <el-form-item label="项目进展状态">
          <el-select v-model="demandForm.status" style="max-width: 150px">
            <el-option
              v-for="(v, i) in demandStatus"
              :key="i"
              :value="i"
              :label="v"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addDemandFun">立即创建</el-button>
        </div>
      </template>
    </el-dialog>
    <demand-dialog
      v-if="demandDetailsDisplay"
      v-model="demandDetailsDisplay"
      :demand-id="demainDetailsId"
    />
  </div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from "vue";
import {
  demandStatus,
  demandType,
  priorityStatus
} from "@/constants/project.ts";
import {
  createDemand,
  deleteDemand,
  demandList,
  taskDemand
} from "@/api/demand.ts";
import ProjectSelector from "@/components/Selector/ProjectSelector.vue";
import { ElMessage } from "element-plus";
import UserSelector from "@/components/Selector/UserSelector.vue";
import { uploadFile } from "@/api/file.ts";
import { stdTime } from "@/utils/time.ts";
import DemandDialog from "@/components/dialog/demandDialog.vue";

defineOptions({
  name: "requirement"
});
let activeIndex = ref("1");
let tableData = ref([]);
let query = ref({
  current: 1,
  size: 10,
  keyword: "",
  status: [] as number[]
});
let pageTotal = ref<number>(0);
let projectId = ref("0");
async function getList() {
  let res: any;
  switch (activeIndex.value) {
    case "1":
      if (!projectId.value) return;
      if (new Date().getTime() - lastTime.getTime() > 500)
        lastTime = new Date();
      else return;
      res = await demandList({ ...query.value, projectId: projectId.value });
      break;
    case "2":
      if (new Date().getTime() - lastTime.getTime() > 500)
        lastTime = new Date();
      else return;
      res = await taskDemand({
        ...query.value,
        projectId: projectId.value
      });
      break;
  }
  if (res) {
    tableData.value = res.data.records;
    pageTotal.value = res.data.total;
  }
}
function pageSizeChange(pageSize) {
  query.value.size = pageSize;
  query.value.current = 1;
  getList();
}
// 数据页码变化
function currPageChange(pageIndex) {
  query.value.current = pageIndex;
  getList();
}
watch(activeIndex, (nv, ov) => {
  projectId.value = "";
  query.value = {
    current: 1,
    size: 10,
    keyword: "",
    status: [] as number[]
  };
  tableData.value = [];
  nextTick(() => {
    getList();
  });
});
onMounted(() => {
  getList();
});
let lastTime = new Date();
watch(projectId, () => {
  getList();
});
watch(
  query,
  () => {
    getList();
  },
  { deep: true }
);
async function deleteDemandFun(id) {
  let res = await deleteDemand(id);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功"
    });
    await getList();
  } else {
    ElMessage({
      type: "error",
      message: res.msg
    });
  }
}
let addDemandDisplay = ref(false);
function openAddDemand() {
  addDemandDisplay.value = true;
  demandForm.value = {
    projectId: projectId.value,
    priority: 1,
    name: "",
    description: "",
    startTime: "",
    endTime: "",
    status: 0,
    type: 0
  };
  attachmentsFileList.value = [];
}
let attachmentsFileList = ref([]);
let demandForm = ref({
  priority: 1,
  name: "",
  description: "",
  startTime: "",
  endTime: "",
  status: 0,
  type: 0
});
let demandDetailsDisplay = ref(false);
let demainDetailsId = ref();
async function openDemandDetails(id) {
  demainDetailsId.value = id;
  demandDetailsDisplay.value = true;
}
async function handleFileUpload(file) {
  let res = await uploadFile(file.file);
  if (res.code === 200) {
    for (let item of attachmentsFileList.value) {
      if (item.uid == file.file.uid) {
        item.url = res.data.url;
      }
    }
    for (let item of attachmentsFileList.value) {
      if (item.uid == file.file.uid) {
        item.url = res.data.url;
      }
    }
  }
}
async function addDemandFun() {
  let { startTime, endTime } = demandForm.value;
  startTime = startTime ? stdTime(startTime) : undefined;
  endTime = endTime ? stdTime(endTime) : undefined;
  let res = await createDemand({
    ...demandForm.value,
    startTime,
    endTime,
    attachments: attachmentsFileList.value.map(({ name, url }) => ({
      filename: name,
      url: url
    }))
  });
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "创建成功"
    });
    addDemandDisplay.value = false;
    await getList();
  } else {
    ElMessage({
      type: "error",
      message: res.msg
    });
  }
}
</script>
